/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assisisw.smartcal.webuisubsystem.managedbean.validator;

import java.util.Objects;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author Francesco
 */
@ManagedBean ( name = "passwordValidator" )
public class PasswordValidator implements Validator 
{

    // Static Fields
    
    /***/
    private static final FacesMessage noContentErrorMessage = new FacesMessage ( "Password required !" ) ;
    
    /***/
    private static final FacesMessage wrongFormatErrorMessage = new FacesMessage ( "Wrong format !" ) ;
    
    /***/
    private static final int MIN_PASSWORD_SIZE = 5 ;
    
    /***/
    private static final int MAX_PASSWORD_SIZE = 25 ;
    
    // Instance Methods
    
    /**
     * AS THE SUPER'S ONE.
     */
    @Override
    public void validate ( FacesContext context , UIComponent component , Object value ) 
            throws ValidatorException 
    {
        FacesMessage errorMessage ;
        String pwd ;
        boolean passwordValid ;
        errorMessage = null ;
        if ( Objects.nonNull ( value ) && ! value.toString ().isEmpty () )
        {
            pwd = value.toString () ;
            if ( pwd.length () < MIN_PASSWORD_SIZE && pwd.length() > MAX_PASSWORD_SIZE )
            {
                errorMessage = wrongFormatErrorMessage ;
                passwordValid = false ;
            }
            else
                passwordValid = true ;
        }
        else
        {
            errorMessage = noContentErrorMessage ;
            passwordValid = false ;
        }
        if ( Objects.nonNull ( errorMessage ) )
            throw new ValidatorException ( errorMessage ) ;
    }

}
